package org.ragdollcat.first.api.ai.aliyun.service;


import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.ragdollcat.first.api.ai.aliyun.model.CreateOutPaintingTaskRequest;
import org.ragdollcat.first.api.ai.aliyun.model.CreateOutPaintingTaskResponse;
import org.ragdollcat.first.api.ai.aliyun.model.GetOutPaintingTaskResponse;
import org.ragdollcat.first.exception.ErrorCode;
import org.ragdollcat.first.exception.ThrowUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


@Slf4j
@Component
public class AliyunAIService {

    @Value("${aliYunAi.apiKey}")
    private String apiKey;

    /**
     * 创建任务获取任务ID请求地址
     */
    private final String createTaskHttpPostUrl = "https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/out-painting";

    /**
     * 查询任务结果请求地址
     */
    private final String queryTaskResHttpGetUrl = "https://dashscope.aliyuncs.com/api/v1/tasks/";


    /**
     * 创建任务获取任务ID
     *
     * @param request
     * @return
     */
    public CreateOutPaintingTaskResponse createTaskHttpPost(CreateOutPaintingTaskRequest request) {
        ThrowUtils.throwIf(ObjUtil.isEmpty(request), ErrorCode.PARAMS_ERROR, "请求参数为空");
        // 发送POST请求
        HttpRequest httpRequest = HttpRequest.post(createTaskHttpPostUrl)
                .header("X-DashScope-Async", "enable")
                .header("Authorization", "Bearer " + apiKey)
                .header("Content-Type", "application/json")
                .body(JSONUtil.toJsonStr(request));

        //解析结果
        try (HttpResponse httpResponse = httpRequest.execute()) {
            ThrowUtils.throwIf(!httpResponse.isOk(), ErrorCode.OPERATION_ERROR, "创建任务失败！");
            CreateOutPaintingTaskResponse response = JSONUtil.toBean(httpResponse.body(), CreateOutPaintingTaskResponse.class);
            ThrowUtils.throwIf(ObjUtil.isEmpty(response), ErrorCode.OPERATION_ERROR, "响应结果为空！");
            ThrowUtils.throwIf(!response.getOutput().getTaskStatus().equals("PENDING"), ErrorCode.OPERATION_ERROR, "响应状态异常！");
            return response;
        }
    }

    /**
     * 根据任务ID查询任务结果
     *  这里不能因为返回的不是success就返回前端失败，因为前端需要轮询，可能任务在处理中
     * @param taskId
     * @return
     */
    public GetOutPaintingTaskResponse createQueryTaskResHttpGet(String taskId) {
        log.info("任务ID:{},开始执行",taskId);
        ThrowUtils.throwIf(StrUtil.isBlank(taskId), ErrorCode.PARAMS_ERROR, "请求参数为空");
        // 发送Get请求
        HttpRequest httpRequest = HttpRequest.get(queryTaskResHttpGetUrl + taskId).header("Authorization", "Bearer " + apiKey);
        //解析结果
        try (HttpResponse httpResponse = httpRequest.execute()) {
            GetOutPaintingTaskResponse response = JSONUtil.toBean(httpResponse.body(), GetOutPaintingTaskResponse.class);
            ThrowUtils.throwIf(ObjUtil.isEmpty(response), ErrorCode.OPERATION_ERROR, "响应结果为空！");
            log.info("任务ID:{},执行完成",taskId);
            return response;
        }
    }
}
